<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="班组名称" prop="teamName">
                <el-input
                        v-model="queryParams.teamName"
                        placeholder="请输入班组名称"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['ar_check:team:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['ar_check:team:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['ar_check:team:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="Upload" @click="handleTeamImport"
                           v-hasPermi="['system:user:import']">
                    导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['ar_check:team:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="班组编号" align="center" prop="teamId"/>
            <el-table-column label="班组名称" align="center" prop="teamName"/>
            <el-table-column label="创建人" align="center" prop="createBy"/>
            <el-table-column label="创建时间" align="center" prop="createTime"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="{row}">
                    <el-button link type="primary" icon="Memo" @click="showMember(row)"
                               v-hasPermi="['ar_check:team:query']">
                        查看成员
                    </el-button>
                    <el-button link type="primary" icon="List" @click="showDefect(row)"
                               v-hasPermi="['ar_check:team:query']">
                        查看巡检情况
                    </el-button>
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(row)"
                               v-hasPermi="['ar_check:team:edit']">修改
                    </el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(row)"
                               v-hasPermi="['ar_check:team:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改班组对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="teamRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="班组名称" prop="teamName">
                    <el-input v-model="form.teamName" placeholder="请输入班组名称"/>
                </el-form-item>
                <el-divider content-position="center">成员信息</el-divider>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="Plus" @click="handleAddTeamMember">添加</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" icon="Delete" @click="handleDeleteTeamMember">删除</el-button>
                    </el-col>
                </el-row>
                <div class="list">
                    <el-table :data="teamMemberList" width="500px" :row-class-name="rowTeamMemberIndex"
                              @selection-change="handleTeamMemberSelectionChange"
                              ref="teamMember">
                        <el-table-column type="selection" width="50" align="center"/>
                        <el-table-column label="序号" align="center" prop="index" width="50"/>
                        <el-table-column label="成员姓名" prop="name" width="150">
                            <template #default="{row}">
                                <el-select v-model="row.memberId" clearable placeholder="请选择成员姓名"
                                           @change="checkClick(row)">
                                    <el-option v-for="item in memberList" :key="item.memberId" :label="item.name"
                                               :value="item.memberId" :disabled="item.disable"/>
                                </el-select>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 班组导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload :action="upload.url" ref="uploadRef" :limit="1" accept=".xlsx, .xls"
                       :on-progress="handleFileProgress"
                       :disabled="upload.isUploading" :auto-upload="false" drag
                       :headers="upload.headers" :on-success="handleFileSuccess">

                <!--icon 标签-->
                <el-icon class="el-icon--upload">
                    <UploadFilled/>
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xlsx格式文件。</span>
                        <!--下载模版-->
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                                 @click="importTemplate">
                            下载模板
                        </el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <!--确定后下载-->
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 查看班组成员 -->
        <el-dialog :title="member.title" v-model="member.open" width="600px" append-to-body>
            <el-table v-loading="loading" :data="member.list">
                <el-table-column label="成员姓名" align="center" prop="name"/>
                <el-table-column label="创建人" align="center" prop="createBy"/>
                <el-table-column label="创建时间" align="center" prop="createTime"/>
            </el-table>
        </el-dialog>
        <defect-list ref="defectTab"/>
    </div>
</template>

<script setup>
import { listTeam, getTeam, delTeam, addTeam, updateTeam } from '@/api/ar_check/team'
import { getMemberByTeamId, memberListQuery } from '@/api/ar_check/member.js'
import { UploadFilled } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth.js'
import { getTeamByIdDefect } from '@/api/ar_check/defects.js'
import DefectList from '@/views/ar_check/defects/components/defectList.vue'

defineOptions({
    name: 'Team'
})

const { proxy } = getCurrentInstance()

const teamList = ref([])
const teamMemberList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedTeamMember = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const memberList = ref([])

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamName: null,
    },
    rules: {
        teamName: [
            { required: true, message: '班组名称不能为空', trigger: 'blur' }
        ],
    }
})

const { queryParams, form, rules } = toRefs(data)

/*** 用户导入参数 */
const upload = ref({
    open: false,
    title: '班组导入',
    // 是否禁用上传
    isUploading: false,
    headers: { Authorization: 'Bearer ' + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + '/ar_check/team/importData'
})

/*班组成员*/
const member = ref({
    open: false,
    list: null,
    title: ''
})

/** 查询班组列表 */
function getList() {
    loading.value = true
    listTeam(queryParams.value).then(response => {
        teamList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

/*查询成员*/
async function getListMember() {
    const { data } = await memberListQuery()
    memberList.value = data.map(value => {
        return { ...value, disable: !!value.teamId }
    })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}

// 表单重置
function reset() {
    form.value = {
        teamId: null,
        teamName: null,
        createTime: null,
        createBy: null
    }
    teamMemberList.value = []
    proxy.resetForm('teamRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.teamId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    getListMember()
    open.value = true
    title.value = '添加班组'
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    const _teamId = row.teamId || ids.value
    getListMember()
    getTeam(_teamId).then(response => {
        form.value = response.data
        teamMemberList.value = response.data.teamMemberList.map(value => {
            return { ...value, id: value.memberId }
        })
        open.value = true
        title.value = '修改班组'
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['teamRef'].validate(valid => {
        if (valid) {
            form.value.teamMemberList = teamMemberList.value
            if (form.value.teamId != null) {
                updateTeam(form.value).then(response => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                })
            } else {
                addTeam(form.value).then(response => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _teamIds = row.teamId || ids.value
    proxy.$modal.confirm('是否确认删除班组编号为"' + _teamIds + '"的数据项？').then(function () {
        return delTeam(_teamIds)
    }).then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
    }).catch(() => {
    })
}

/** 成员序号 */
function rowTeamMemberIndex({ row, rowIndex }) {
    row.index = rowIndex + 1
}

/** 成员添加按钮操作 */
function handleAddTeamMember() {
    let obj = {}
    obj.memberId = null
    obj.id = null
    teamMemberList.value.push(obj)
}

/** 成员删除按钮操作 */
function handleDeleteTeamMember() {
    if (checkedTeamMember.value.length === 0) {
        proxy.$modal.msgError('请先选择要删除的成员数据')
    } else {
        const checkedTeamMembers = checkedTeamMember.value
        checkedTeamMembers.forEach(value => {
            const data = teamMemberList.value.find(val => val.index === value)
            disableCheck(data.memberId, false)
            data.id = ''
        })
        teamMemberList.value = teamMemberList.value.filter(function (item) {
            return checkedTeamMembers.indexOf(item.index) === -1
        })
    }
}

/** 复选框选中数据 */
function handleTeamMemberSelectionChange(selection) {
    checkedTeamMember.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('ar_check/team/export', {
        ...queryParams.value
    }, `team_${new Date().getTime()}.xlsx`)
}

/*选中成员*/
function checkClick(row) {
    if (row.memberId) {
        if (row.id)
            disableCheck(row.id, false)
        row.id = row.memberId
        disableCheck(row.memberId, true)
    } else {
        disableCheck(row.id, false)
        row.id = ''
    }
}

/*禁用开关*/
function disableCheck(id, flag) {
    if (!id) return
    const member = memberList.value.find(value => value.memberId === id)
    member.disable = flag
}

// 打开导入
function handleTeamImport() {
    upload.value.open = true
}

// 文件上传中
function handleFileProgress() {
    upload.value.isUploading = true
}

// 文件上传完成
function handleFileSuccess(response, file) {
    upload.value.open = false
    upload.value.isUploading = false
    proxy.$refs['uploadRef'].handleRemove(file)
    proxy.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' +
        response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
    getList()
}

// 下载模板
function importTemplate() {
    proxy.download('ar_check/team/importTemplate', {}, `team_template_${new Date().getTime()}.xlsx`)
}

// 确定上传
async function submitFileForm() {
    proxy.$refs.uploadRef.submit()
}

// 查看班组成员
async function showMember(row) {
    loading.value = true
    const { data } = await getMemberByTeamId(row.teamId)
    member.value.list = data
    member.value.title = row.teamName
    loading.value = false
    member.value.open = true
}

// 查看缺陷设备
async function showDefect({ teamId, teamName }) {
    const { data } = await getTeamByIdDefect(teamId)
    proxy.$refs.defectTab.open(data, teamName)
}

getList()
</script>

<style>
.list .el-table__header {
    width: 100% !important;
}

.list .el-table__body {
    width: 100% !important;
}
</style>
